﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using System.Net;
using System.Web;
using System.Runtime.Serialization.Json;

namespace WebApplication1
{
    // NOTE: If you change the class name "GdiStoryService" here, you must also update the reference to "GdiStoryService" in Web.config.
    public class GdiStoryService : IGdiStoryService
    {
        const string GOOGLE_SEARCH_URL = "http://ajax.googleapis.com/ajax/services/search/web?v={0}&q={1}&rsz={2}&start={3}";
        const string GOOGLE_NEWS_URL = "http://ajax.googleapis.com/ajax/services/search/news?v={0}&q={1}";
        const string GOOGLE_SERACH_API_VERSION = "1.0";
        string resultSize = "large";
        int PAGE_SIZE = 8;
        string lastPhrase = "";
        int startIndex = 0;

        public List<Story> GetStories()
        {
            List<Story> stories = new List<Story>();

            XmlDocument doc = new XmlDocument();
            doc.Load("http://ny614070.bhsrv.com/GdiConfiguration/PageConfiguration.xml");

            XmlNodeList nodes = doc.GetElementsByTagName("Story");

            foreach (XmlNode node in nodes)
            {
                Story s = new Story();
                foreach (XmlNode child in node)
                {
                    if (child.Name == "ImageUri")
                    {
                        s.ImageUrl = child.InnerText;
                    }
                    else if (child.Name == "Headline")
                    {
                        s.TitleNoFormatting = child.InnerText;
                    }
                    else if (child.Name == "Description")
                    {
                        s.Content = child.InnerText;
                    }
                }

                stories.Add(s);
            }

            return stories;
        }

        public List<Product> GetProducts()
        {
            List<Product> returnProducts = new List<Product>();

            XmlDocument doc = new XmlDocument();
            doc.Load("http://ny614070.bhsrv.com/GdiConfiguration/PageConfiguration.xml");

            XmlNodeList nodes = doc.GetElementsByTagName("Product");

            foreach (XmlNode node in nodes)
            {
                Product p = new Product();
                foreach (XmlNode child in node)
                {
                    if (child.Name == "ImageUri")
                    {
                        p.ImageUrl = child.InnerText;
                    }
                    else if (child.Name == "Headline")
                    {
                        p.TitleNoFormatting = child.InnerText;
                    }
                    else if (child.Name == "Description")
                    {
                        p.Content = child.InnerText;
                    }
                }
                returnProducts.Add(p);
            }
            return returnProducts;
        }

        public List<GoogleNewsResult> SearchGoogleNews(string searchQuery)
        {
            List<GoogleNewsResult> results = new List<GoogleNewsResult>();
            WebClient client = new WebClient();

            Stream data = client.OpenRead(new Uri(string.Format(GOOGLE_NEWS_URL, GOOGLE_SERACH_API_VERSION, HttpUtility.UrlEncode(searchQuery))));

            XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(data, XmlDictionaryReaderQuotas.Max);

            while (reader.Read())
            {
                if (reader.LocalName == "GsearchResultClass")
                {
                    GoogleNewsResult resultItem = new GoogleNewsResult();
                    reader.ReadToFollowing("content");
                    resultItem.Content = reader.ReadElementContentAsString();
                    reader.MoveToContent();
                    resultItem.UnescapedUrl = reader.ReadElementContentAsString();
                    reader.MoveToContent();
                    resultItem.Url = reader.ReadElementContentAsString();
                    reader.ReadToFollowing("titleNoFormatting");
                    //reader.MoveToContent();
                    resultItem.TitleNoFormatting = reader.ReadElementContentAsString();
                    reader.ReadToFollowing("publishedDate");
                    //reader.MoveToContent();
                    resultItem.PublishedDate = reader.ReadElementContentAsString();
                    reader.ReadToFollowing("image");

                    reader.ReadToDescendant("url");
                    resultItem.ImageUrl = reader.ReadElementContentAsString();

                    reader.ReadToFollowing("relatedStories");
                    

                    results.Add(resultItem);
                }

            }

            return results;
        }

        public List<GoogleSearchResult> SearchGoogle(string searchQuery)
        {
            List<GoogleSearchResult> results = new List<GoogleSearchResult>();
            WebClient client = new WebClient();

            Stream data = client.OpenRead(new Uri(string.Format(GOOGLE_SEARCH_URL, GOOGLE_SERACH_API_VERSION, HttpUtility.UrlEncode(searchQuery),resultSize,startIndex)));

            List<GoogleSearchResult> resultList = new List<GoogleSearchResult>();

            XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(data, XmlDictionaryReaderQuotas.Max);

            results.Clear();
            while (reader.Read())
            {
                //string xml = reader.ReadOuterXml();
                if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "cursor") break;
                if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "item")
                {
                    GoogleSearchResult resultItem = new GoogleSearchResult();
                    reader.ReadToDescendant("unescapedUrl");
                    resultItem.UnescapedUrl = reader.ReadElementContentAsString();
                    reader.MoveToContent();
                    resultItem.Url = reader.ReadElementContentAsString();
                    reader.MoveToContent();
                    resultItem.VisibleUrl = reader.ReadElementContentAsString();
                    reader.ReadToFollowing("titleNoFormatting");
                    reader.MoveToContent();
                    resultItem.TitleNoFormatting = reader.ReadElementContentAsString();
                    reader.MoveToContent();
                    resultItem.Content = reader.ReadElementContentAsString();

                    resultList.Add(resultItem);
                    results.Add(resultItem);
                }
            }

            return results;
        }
    }
}
